﻿using System.Net.Http;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Collections.Generic;
using System;
using System.Collections.Specialized;
using System.Text;

public class comm
{
    public static string PostMultipartFormData(string url, Dictionary<string, string> headers, NameValueCollection nameValueCollection, NameValueCollection fileCollection)
    {
        using (var client = new HttpClient())
        {
            foreach (var item in headers)
            {
                client.DefaultRequestHeaders.Add(item.Key, item.Value);
            }

            using (var content = new MultipartFormDataContent())
            {
                // 键值对参数
                string[] allKeys = nameValueCollection.AllKeys;
                foreach (string key in allKeys)
                {
                    var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key]));
                    dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                    {
                        Name = key
                    };
                    content.Add(dataContent);
                }

                //处理文件内容
                string[] fileKeys = fileCollection.AllKeys;
                foreach (string key in fileKeys)
                {
                    byte[] bmpBytes = File.ReadAllBytes(fileCollection[key]);
                    var fileContent = new ByteArrayContent(bmpBytes);//填充文件字节
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                    {
                        Name = key,
                        FileName = Path.GetFileName(fileCollection[key])
                    };
                    content.Add(fileContent);
                }

                var result = client.PostAsync(url, content).Result;//post请求
                string data = result.Content.ReadAsStringAsync().Result;
                return data;//返回操作结果
            }
        }
    }
}